package com.dyit.controller;

import com.dyit.dto.HttpResp;
import com.dyit.entity.Book;
import com.dyit.entity.User;
import com.dyit.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "用户进行操作")
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private IUserService ius;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 用户登录
     * @param account
     * @param password
     * @return
     */
    @ApiOperation("用户登录模块")
    @GetMapping("/login")
    public HttpResp login(String account,String password){
        User user=ius.login(account,password);
        //从业务逻辑层拿到user对象了之后，放进redis缓存里
        redisTemplate.opsForValue().set("currentuser",user);//把当前用户对象存到缓存里
        redisTemplate.opsForValue().set("currentuserper",user.getPer());//把当前的用户权限也存进去
//        System.out.println(redisTemplate.opsForValue().get("currentuser"));
        return new HttpResp(20001,"用户登陆成功！",user,null);
    }

    /**
     * 根据图书馆id查询该图书馆下的所有书信息
     * @param library_id
     * @return
     */
    @ApiOperation("根据图书馆id找书")
    @GetMapping("/findAllBookByLibraryId")
    public HttpResp findAllBookByLibraryId(int library_id){
        List<Book>  list = ius.findAllBooks(library_id);
        if(redisTemplate.opsForValue().get("library"+library_id)!=null){
            return new HttpResp(30000,"查询该图书馆成功！",redisTemplate.opsForValue().get("library"+library_id),null);
        }
        redisTemplate.opsForValue().set("library"+library_id,list);//把当前对象放到缓存里，（library1，书列表）
        return new HttpResp(30000,"查询该图书馆的书成功！",list,null);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @ApiOperation("用户注册")
    @GetMapping("/registry")
    public HttpResp registry(User user){
        ius.addUser(user);
        return new HttpResp(20002,"注册成功！",user.getAccount(),null);
    }











    /**
     * 用户根据自己的id查询借阅记录
     * @param user_id
     * @return
     */
//    @ApiOperation("根据用户id查询自己的借书记录")
//    @GetMapping("/findBorrowHistoryByUser_id")
//    public HttpResp findBorrowHistoryByUser_id(int user_id){
//        List<BorrowTwo> list = ius.findBorrowHistoryByUser_id(user_id);//取得了本人的借阅记录列表
//        return new HttpResp(30000,"查询借阅记录成功！",list,null);
//    }

}
